;
window.Page = function() {
	"use strict";
	console.log("速卖通~~~");
	var $menusList = $("#menusList"), menusList, infoMap = {}, colorMap = {}, colorList = [], sizeList = [], isClothing;
	var $msgBox = $('<div class="msg-box"></div>'), time;
	$("body").append($msgBox);
	return {
		// basePath:"https://localhost:8443/AliexpressRASys",
		basePath : "https://www.cocotuku.com/AliexpressRASys",
		createMenuItem : function(id, name, callback) {
			// 创建菜单项
			var menuItem = document.createElement("div");
			menuItem.setAttribute("class", "web-context-menu-item");
			menuItem.setAttribute("id", "menu-item-" + id);
			// 菜单项中的span，菜单名
			var span = document.createElement("span");
			span.setAttribute("class", "menu-item-name");
			span.innerText = name;
			if (callback && typeof callback === 'function') {
				span.addEventListener("click", function() {
					callback.call(this, id);
				});
			}
			// 创建小箭头
			var i = document.createElement("i");
			i.innerText = "▲";
			span.appendChild(i);
			// 创建下一层菜单的容器
			var subContainer = document.createElement("div");
			subContainer.setAttribute("class", "web-context-menu-items");
			menuItem.appendChild(span);
			menuItem.appendChild(subContainer);
			return menuItem;
		},
		// 创建菜单项之间的分隔线条
		createLine : function() {
			var line = document.createElement("div");
			line.setAttribute("class", "menu-item-line");
			return line;
		},
		/**
		 * 创建菜单
		 */
		createMenu : function(menuArr) {
			// 创建菜单层
			var menu = document.createElement("div");
			menu.setAttribute("class", "web-context-menu");
			menu.setAttribute("id", "web-context-menu");
			document.querySelector("body").appendChild(menu);
			// 创建菜单项容器
			var menuItemsContainer = document.createElement("div");
			menuItemsContainer.setAttribute("class", "web-context-menu-items");
			menu.appendChild(menuItemsContainer);
			// 遍历菜单项
			for (var i = 0; i < menuArr.length; i++) {
				var menuItem = menuArr[i];
				var parent = menuItem.parent;
				// 创建菜单项
				var oneMenu = Page.createMenuItem(menuItem.id, menuItem.name, menuItem.callback);
				if (!parent) {
					menuItemsContainer.appendChild(oneMenu);
					menuItemsContainer.appendChild(Page.createLine());
				} else {
					var parentNode = document.querySelector("#menu-item-" + parent + " .web-context-menu-items");
					parentNode.appendChild(oneMenu);
					parentNode.appendChild(Page.createLine());
				}
			}
			// 遍历菜单项去掉没有子菜单的菜单项的小箭头
			var allContainer = menu.querySelectorAll(".web-context-menu-items");
			for (var i = 0; i < allContainer.length; i++) {
				var oneContainer = allContainer[i];
				if (!oneContainer.hasChildNodes()) {
					var iTag = oneContainer.parentElement.querySelector("i")
					iTag.parentElement.removeChild(iTag);
				}
			}
		},
		getMenus : function(menusList) {
			$.ajax({
				cache : true,
				url : Page.basePath + "/cross/menuList",
				type : 'POST',
				success : function(data) {
					if ("true" == data.code) {
						var list = data.list, menuList = [], record;
						if (list && list.length > 0) {
							for (var i = 0, a = list.length; i < a; i++) {
								record = list[i];
								menuList.push({
									name : record.menuName,
									id : record.id,
									parent : null == record.parentId ? null : record.parentId,
									callback : function(id) {
										Page.selectData(id);
									}
								});
							}
							Page.createMenu(menuList);
						}
					} else {
						Page.showMsg(2, "加载菜单失败！");
					}
				},
				error : function() {
					Page.showMsg(2, "服务异常！");
				}
			});
		},
		selectData : function(menuId) {
			$.ajax({
				cache : true,
				url : Page.basePath + "/cross/menuInfo/" + menuId,
				type : 'POST',
				success : function(data) {
					if ("true" == data.code) {
						var obj = data.object;
						if (obj) {
							if (obj.templates && obj.templates.length > 0) {
								isClothing = obj.isClothing;
								var $category = $("#categoryHistoryId");
								var $option = $category.find("option[value='" + obj.categoryId + "']");
								if ($option.length == 0 && obj.categoryName) {
									var categoryNames = obj.categoryName.split(">");
									$option = $('<option value="' + obj.categoryId + '">' + categoryNames[categoryNames.length - 1] + '</option>');
									$category.append($option);
								}
								obj.categoryId && $category.val(obj.categoryId).trigger("change");
								Page.selectAttribute(obj);// 选择属性
								Page.selectProductInfo();
								Page.showMsg(1, "操作成功！");
							} else {
								Page.showMsg(2, "菜单“" + obj.menuName + "”未配置模板！");
							}
						} else {
							Page.showMsg(2, "查询失败！");
						}
					} else {
						Page.showMsg(2, "查询失败！");
					}
				},
				error : function() {
					Page.showMsg(2, "服务异常！");
				}
			});
		},
		showMsg : function(type, msg) {
			var cls1 = 1 == type ? "success" : "error";
			var cls2 = 1 == type ? "error" : "success";
			clearTimeout(time);
			$msgBox.removeClass(cls2).addClass(cls1).html(msg).fadeIn(function() {
				time = setTimeout(function() {
					$msgBox.fadeOut();
				}, 5000);
			});
		},
		selectAttribute : function(obj) {
			var $productAttribute = $("#productAttribute table");
			if (0 == $productAttribute.length) {
				setTimeout(function() {
					Page.selectAttribute(obj);
				}, 1000);
			} else {
				setTimeout(function() {
					var templates = obj.templates;
					if (templates && templates.length > 0) {
						var template = null, attrId, $input, $selected;
						for (var i = 0, a = templates.length; i < a; i++) {
							template = templates[i];
							attrId = template.attrName;
							attrId && (attrId = attrId.replace("attr", ""));
							if ("list_box" == template.attrType) {
								$input = $productAttribute.find("select[attrid='" + attrId + "']");
								$selected = $input.find("option[data-cid='" + template.attrValues + "']");
								$selected.attr("selected", "selected").val(template.attrValues);
								$input.trigger("chosen:updated");
							} else if ("input" == template.attrType) {
								$input = $productAttribute.find("#" + attrId).closest("tr").find("input");
								$input.val(template.attrValues);
							} else if ("check_box" == template.attrType) {
								if (template.attrValues) {
									var values = template.attrValues.split(",");
									for (var j = 0, b = values.length; j < b; j++) {
										$productAttribute.find("input[name='check" + attrId + "'][data-cid='" + values[j] + "']").prop("checked", true);
									}
								}
							}
						}
					}
				}, 1000);
			}
		},
		// 选择产品属性
		selectProductInfo : function() {
			infoMap = {};
			colorMap = {};
			colorList = [];
			sizeList = [];
			var $subject = $("#subject"), $skuAttribute = $("#skuAttribute"), selectedSizes = [];
			$.ajax({
				cache : true,
				url : Page.basePath + "/cross/productInfo/" + $subject.val(),
				type : 'POST',
				success : function(data) {
					if ("true" == data.code) {
						var list = data.list;
						if (list && list.length > 0) {
							var record = null, key;
							for (var i = 0, a = list.length; i < a; i++) {
								key = "";
								record = list[i];
								if (record.color) {
									key = record.color;
									(-1 == $.inArray(record.color, colorList)) && colorList.push(record.color);
								}
								if (record.size && isClothing) {
									if (key) {
										key += "-" + record.size;
									} else {
										key = record.size;
									}
									(-1 == $.inArray(record.size, sizeList)) && sizeList.push(record.size);
								}
								key && (infoMap[key] = record);
							}
							var $span = $skuAttribute.find("table td>span:contains('颜色：')");
							if (colorList.length > 0 && $span.length > 0) {
								var $tr = $span.closest("tr"), $this;
								$tr.children("td:eq(1)").find("input:checkbox").each(function(index) {
									if (index < colorList.length) {
										$this = $(this);
										$this.click();
										// 用以核对子sku
										colorMap[$this.data("cid")] = $this.attr("nameen").replace(/\s/g, '%20');
									} else {
										return false;
									}
								});
								$tr.next("tr").find("table.myj-table input").each(function(index) {
									$(this).val(colorList[index]);
									colorMap[colorList[index]] = $(this).closest("td").prev("td").attr("cid");
								});
							}
							if (0 == sizeList.length && 0 == colorList.length) {
								record = list[0];
								$("#ipmSkuStock").val(1000).trigger("keyup");
								$("#skuCode").val(record.sku).trigger("keyup");
							} else if (isClothing) {// 只有服装选择尺寸
								var $span = $skuAttribute.find("table td>span:contains('尺寸：')");
								if (sizeList.length > 0 && $span.length > 0) {
									var $td = $span.closest("tr").children("td:eq(1)"), $check;
									for (var j = 0, b = sizeList.length; j < b; j++) {
										$check = $td.find("input[namezh='" + sizeList[j] + "'],input[nameen='" + sizeList[j] + "']");
										if ($check.length > 0) {
											$check.click();
											selectedSizes.push(sizeList[j]);// 选中的尺寸
										}
									}
								}
								var $variant = null, variant, $table = $("#skuVariantList>table.myj-table");
								for (var x = 0, c = colorList.length; x < c; x++) {
									for (var y = 0, d = selectedSizes.length; y < d; y++) {
										variant = infoMap[colorList[x] + "-" + selectedSizes[y]];
										$variant = $table.find("tr[trid='" + colorMap[colorMap[colorList[x]]] + selectedSizes[y] + "']")
										if ($variant.length > 0) {
											if (variant) {
												$variant.find("td[data-names='price']>input").val(variant.price).trigger("keyup");
												$variant.find("td[data-names='num']>input").val(1000).trigger("keyup");
												$variant.find("td[data-names='sku']>input").val(variant.sku).trigger("keyup");
											} else {
												$variant.find("td[data-names='price']>input").val(0).trigger("keyup");
												$variant.find("td[data-names='num']>input").val(0).trigger("keyup");
												$variant.find("td[data-names='sku']>input").val(variant.parentSku.split("-")[0] + Math.floor(Math.random() * 9000) + 1000).trigger("keyup");
											}
										}
									}
								}
							} else {
								var $variant = null, variant, $table = $("#skuVariantList>table.myj-table");
								for (var x = 0, c = colorList.length; x < c; x++) {
									variant = infoMap[colorList[x]];
									$variant = $table.find("tr[trid='" + colorMap[colorMap[colorList[x]]] + "']")
									if ($variant.length > 0) {
										if (variant) {
											$variant.find("td[data-names='price']>input").val(variant.price).trigger("keyup");
											$variant.find("td[data-names='num']>input").val(1000).trigger("keyup");
											$variant.find("td[data-names='sku']>input").val(variant.sku).trigger("keyup");
										} else {
											$variant.find("td[data-names='price']>input").val(0).trigger("keyup");
											$variant.find("td[data-names='num']>input").val(0).trigger("keyup");
											$variant.find("td[data-names='sku']>input").val(variant.parentSku.split("-")[0] + Math.floor(Math.random() * 9000) + 1000).trigger("keyup");
										}
									}
								}
							}
						} else {
							Page.showMsg(2, "查询产品信息失败！");
						}
					} else {
						Page.showMsg(2, "查询产品信息失败！");
					}
				},
				error : function() {
					Page.showMsg(2, "服务异常！");
				}
			});
		},
		// 产品描述，图片引入
		importImg : function() {
			var text = getEditorData('myj-editor');
			var $html = $("<p>" + text + "</p>"), srcs = [], src;
			$html.find("img").each(function() {
				srcs.push(this.src);
			});
			$("#img_show").find("div.imgDivIn>img").each(function() {
				src = this.src;
				if (srcs.indexOf(src) < 0) {
					$html.append('<img src="' + src + '">');
					srcs.push(src);
				}
			});
			setEditorData('myj-editor', $html.prop("outerHTML"));
			var $module = $("div.productInfoModule");
			$module.find("input:checkbox[uid='wirelessOpen']").click();
			$module.find("a[uid='pcToWireless']").click();
		}
	}
}();
Page.getMenus();
setTimeout(function() {
	Page.importImg();
}, 1000);